import 'package:flutter/material.dart';
import 'package:hairen_app/server/server.dart';
import 'package:hairen_app/server/saveInfo.dart';
import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'common.dart';
import 'favoritesList.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hairen_app/pages/plug/drawer.dart';
class Favorites extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _FavoritesState();
  }
}

class _FavoritesState extends State<Favorites> {
  Map userInfo = {};
  String token = "";
  List favoritesList = [];

  Future getFavorites=Server.getFavorite();

  getInfo() {
    SaveInfo.getUserToken().then((Map ret) {
      setState(() {
        userInfo = ret['userInfo'];
        token = ret['token'];
      });
    });
  }

  final TextEditingController _addText=new TextEditingController();
  final TextEditingController _updateText=new TextEditingController();
  int  select_fid=0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getInfo();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  Future addFavorites() async{
    return   showDialog<Null>(
      context: context,
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        return new AlertDialog(
          title: new Text("添加收藏夹"),
          content: new SingleChildScrollView(
            child: new ListBody(
              children: <Widget>[
                new TextField(
                  decoration: new InputDecoration(
                    hintText: "输入收藏夹的名字",

                  ),
                  controller: _addText,
                ),

              ],
            ),
          ),
          actions: <Widget>[
            new Container(
              child:  new RaisedButton(
                child: new Text('确认',style: new TextStyle( color: Colors.white,),),
                onPressed: () {
                  String text=_addText.text;
                    if(text==""){
                      Fluttertoast.showToast(
                          msg: "请输入收藏夹的名字",
                          gravity: ToastGravity.TOP,
                          toastLength: Toast.LENGTH_SHORT,
                          timeInSecForIos: 1,
                          bgcolor: "#f56464",
                      );
                    }else{
                      Server.addFavorite(data: {"name":text}).then((ret){

                        if(ret['code']==1){
                          Fluttertoast.showToast(
                            msg: ret['msg'],
                            gravity: ToastGravity.TOP,
                            toastLength: Toast.LENGTH_SHORT,
                            timeInSecForIos: 1,
                          );
                          setState(() {
                            getFavorites=Server.getFavorite();
                            _addText.text="";
                          });
                          Navigator.of(context).maybePop();

                        }else{
                          Fluttertoast.showToast(
                            msg: ret['msg'],
                            gravity: ToastGravity.TOP,
                            toastLength: Toast.LENGTH_SHORT,
                            timeInSecForIos: 1,
                          );
                        }
                      });
                    }

                },
              ),
              alignment: Alignment.centerLeft,
            ),
            new RaisedButton(
              child: new Text('取消',style: new TextStyle( color: Colors.white,),),
              color: Colors.black12.withOpacity(0.5),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
  Future updateFavorites( ) async{
    return   showDialog<Null>(
      context: context,
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        return new AlertDialog(
          title: new Text("编辑收藏夹"),
          content: new SingleChildScrollView(
            child: new ListBody(
              children: <Widget>[
                new TextField(
                  decoration: new InputDecoration(
                    hintText: "输入收藏夹的名字",
                  ),
                  controller: _updateText,
                ),

              ],
            ),
          ),
          actions: <Widget>[
            new Container(
              child:  new RaisedButton(
                child: new Text('确认',style: new TextStyle( color: Colors.white,),),
                onPressed: () {
                  String text=_updateText.text;
                  if(text==""){
                    Fluttertoast.showToast(
                      msg: "请输入收藏夹的名字",
                      gravity: ToastGravity.TOP,
                      toastLength: Toast.LENGTH_SHORT,
                      timeInSecForIos: 1,
                      bgcolor: "#f56464",
                    );
                  }else{
                    Server.updateFavorite(data: {"name":text,"id":"${select_fid}"}).then((ret){

                      if(ret['code']==1){
                        Fluttertoast.showToast(
                          msg: ret['msg'],
                          gravity: ToastGravity.TOP,
                          toastLength: Toast.LENGTH_SHORT,
                          timeInSecForIos: 1,
                        );
                        setState(() {
                          getFavorites=Server.getFavorite();
                          _addText.text="";
                        });
                        Navigator.of(context).maybePop();

                      }else{
                        Fluttertoast.showToast(
                          msg: ret['msg'],
                          gravity: ToastGravity.TOP,
                          toastLength: Toast.LENGTH_SHORT,
                          timeInSecForIos: 1,
                        );
                      }
                    });
                  }

                },
              ),
              alignment: Alignment.centerLeft,
            ),
            new RaisedButton(
              child: new Text('取消',style: new TextStyle( color: Colors.white,),),
              color: Colors.black12.withOpacity(0.5),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  delFavorite(int id){
    Server.delFavorite(data: {"id":id.toString()}).then((ret){
      if(ret['code']==1){
        Fluttertoast.showToast(
          msg: ret['msg'],
          gravity: ToastGravity.TOP,
          toastLength: Toast.LENGTH_SHORT,
          timeInSecForIos: 1,
        );
        setState(() {
          getFavorites=Server.getFavorite();
          _addText.text="";
        });
        Navigator.of(context).maybePop();

      }else{
        Fluttertoast.showToast(
          msg: ret['msg'],
          gravity: ToastGravity.TOP,
          toastLength: Toast.LENGTH_SHORT,
          timeInSecForIos: 1,
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        title: new Text("我的收藏"),
        leading: new Builder(builder: (context){
          return new IconButton(icon: new Icon(Icons.menu), onPressed:(){
            Scaffold.of(context).openDrawer();
          });
        }),
        actions: <Widget>[
          new IconButton(
              icon: new Icon(Icons.add),
              onPressed: () {
                addFavorites();

              })
        ],
      ),
      drawer: new DrawerPage(),
      body: new CommonPage(
        future:getFavorites,
        child: (data){
          List rows=data['data'];
          return new ListView(
             children: rows.map((item){
               return new ListTile(
                   leading: Icon(
                     Icons.folder,
                     size: 50.0,
                     color: Theme.of(context).iconTheme.color,
                   ),
                   title: new Text("${item['name']}"),
                   subtitle: new Text("${item['count']}个视频"),
                   trailing: new PopupMenuButton(
                     itemBuilder: (BuildContext context) {
                       return [
                         new PopupMenuItem(
                           child: new GestureDetector(
                              child:new Container(
                               child: Text('编辑'),
                              ),
                              onTap: (){
                              Navigator.of(context).pop();
                                this.select_fid=int.parse(item['id']);
                                _updateText.text="${item['name']}";
                               updateFavorites();
                             },
                           ),
                         ),
                         new PopupMenuItem(
                           child: new InkWell(
                             child:new Text('删除'),
                             onTap: (){
                               delFavorite(int.parse(item['id']));
                             },
                           ),
                         ),
                       ];
                     },
                     icon: new Icon(Icons.more_horiz),
                   ),
                   onTap: () {
                            Navigator.of(context).push(
                              new CupertinoPageRoute(builder: (context)=>new FavoritesList(int.parse(item['id']))),
                            );
                   }
                  );
             }).toList(),
           );
        },
        design: new Favorites(),),
    );
  }

}

